import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

import '../../../utils/util.dart';
import '../model/page.dart';
import 'state.dart';

abstract class IRefreshController<S extends IRefreshState>
    extends GetxController {
  late S state = createState();
  S createState();

  @protected
  Future<NetBaseReponse> onRequest({
    int? current,
  });

  Future<void> onRefresh() async {
    state.page?.current = 1;
    var res = await onRequest(current: state.page?.current);
    if (res.data is PageModel) {
      state.page!.update(res, refreshCtrl: state.controller);
    } else {
      state.dataModel = res.data;
      state.controller.finishRefresh();
    }
    updateBody();
  }

  Future<void> onLoading() async {
    if (!canPullup) {
      state.controller.finishLoad(IndicatorResult.noMore);
    } else {
      if (hasNoMore) {
        state.controller.finishLoad(IndicatorResult.noMore);
        updateBody();
        return;
      }
    }
    state.page?.current += 1;
    var res = await onRequest(current: state.page?.current);
    if (res.data is PageModel) {
      state.page!.update(res, refreshCtrl: state.controller);
    }

    updateBody();
  }

  void updateBody() {
    update([state.updateBodyId]);
  }

  bool get canPullup => true;

  bool get hasNoMore {
    if (state.page!.records?.isNotEmpty == true) {
      return !state.page!.hasNext;
    }
    return false;
  }

  @override
  void onInit() {
    state = createState();

    super.onInit();
  }

  @override
  void onReady() {
    onRefresh();

    super.onReady();
  }

  @override
  void dispose() {
    state.controller.dispose();

    super.dispose();
  }
}
